package com.zoweunion.mechanic.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.zoweunion.mechanic.config.AlipayConfig;
import com.zoweunion.mechanic.controller.BaseController;
import com.zoweunion.mechanic.dao.app.AppDao;
import com.zoweunion.mechanic.model.ResponseBean;
import com.zoweunion.mechanic.model.User;
import com.zoweunion.mechanic.plugins.redis.RedisUtil;
import com.zoweunion.mechanic.service.app.AppService;
import com.zoweunion.mechanic.service.base.UpkeepService;
import com.zoweunion.mechanic.service.base.UserService;
import com.zoweunion.mechanic.util.*;
import com.zoweunion.mechanic.util.constants.Constants;
import httpsTrustClient.HTTPSTrustClient;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.HttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Data
@RestController
@RequestMapping("/app")
@SuppressWarnings("all")
public class AppController extends BaseController {

	@Autowired
	private AppService appService;
	@Autowired
	private UserService userService;
	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private AppDao appDap;
	@Autowired
	private UpkeepService upkeepService;

	/**
	 * 获取用户的轨迹id
	 *
	 * @param str
	 * @returngetCarType
	 */
	@PostMapping("/getUserTrid")
	public ResponseBean getUserTrid(@RequestBody String str, HttpServletRequest request) throws MyException {
		logBefore(logger, "获取用户的轨迹id");
		User currentUser = getCurrentUser(request);
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);

		// 获取轨迹id
		Map<String, Object> resultMap = appService.getUserTrid(currentUser, reqMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", resultMap);
	}

	/**
	 * 保存用户的轨迹id
	 *
	 * @param str
	 * @returngetCarType
	 */
	@PostMapping("/saveUserTrid")
	public ResponseBean saveUserTrid(@RequestBody String str, HttpServletRequest request) throws MyException {
		logBefore(logger, "保存用户的轨迹id");
		User currentUser = getCurrentUser(request);
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		// 获取轨迹id
		boolean is = appService.saveUserTrid(currentUser, reqMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", true);
	}

	/**
	 * 是否上线的判断
	 * @param str
	 * @returngetCarType
	 */
	@PostMapping("/isCheck")
	public ResponseBean isCheck(@RequestBody String str,HttpServletRequest request){

		try {

			return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",false);
		} catch (Exception e) {

			return new ResponseBean(Constants.CODE_HANDEL_FAILED, "操作失败", null);
		}
	}

	/**
	 * 获取车辆列表
	 * @param str
	 * @return
	 */
	@PostMapping("/getVehicleList")
	public ResponseBean getVehicleList(@RequestBody String str,HttpServletRequest request){
		logBefore(logger,"获取车辆列表");
		try {

			User user = getCurrentUser(request);

			Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);

			reqMap.put("id",user.getId());
			reqMap.put("s_id",user.getS_id());
			reqMap.put("rId",user.getR_id());

			List<Map<String, Object>>resultMap = appService.getVehicleList(reqMap);

			return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resultMap);
		} catch (Exception e) {
			System.out.println(e.getMessage());
			return new ResponseBean(Constants.CODE_HANDEL_FAILED, "操作失败", null);
		}
	}

	/**
	 * 模糊匹配 获取服务商
	 * @param str
	 * @return
	 */
	@PostMapping("/getService")
	public ResponseBean getServer(@RequestBody String str){
		logBefore(logger,"模糊匹配 获取服务商");
		try {
			Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
			Map<String, Object> resultMap = appService.getServer(reqMap);
			return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resultMap);
		} catch (Exception e) {
			System.out.println(e.getMessage());
			return new ResponseBean(Constants.CODE_HANDEL_FAILED, "操作失败", null);
		}
	}

	/**
	 * 判断服务商有没有绑定此设备
	 * @param str
	 * @return
	 */
	@PostMapping("/getIsServerDevice")
	public ResponseBean getIsServerDevice(@RequestBody String str){
		logBefore(logger,"判断服务商有没有绑定此设备");
		try {
			Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
			int result = appService.getIsServerDevice(reqMap);
			logAfter(logger);
			if (result == 0) {
				return new ResponseBean(Constants.CODE_HANDEL_FAILED, "此设备已绑定服务商", null);
			}
			return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",result);
		} catch (Exception e) {
			return new ResponseBean(Constants.CODE_HANDEL_FAILED, "操作失败", null);
		}
	}

	/**
	 * 扫一扫添加设备
	 * @param str
	 * @param request
	 * @return
	 */
	@PostMapping("/scanAddDevice")
	public ResponseBean scanAddDevice(@RequestBody String str, HttpServletRequest request){
		logBefore(logger,"扫一扫添加设备");
		try {
			Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
			User user = getCurrentUser(request);
			//用户的服务商id
			reqMap.put("sId", user.getS_id());

			//用户id
			reqMap.put("uId", user.getId());
			reqMap.put("create_user", user.getUser_name());
			reqMap.put("update_user", user.getUser_name());
			int result = appService.scanAddDevice(reqMap);
			logAfter(logger);
			if (result == 2) {
				return new ResponseBean(Constants.CODE_HANDEL_FAILED, "设备绑定失败", null);
			}
			return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",result);
		} catch (Exception e) {

			return new ResponseBean(Constants.CODE_HANDEL_FAILED, "操作失败", null);
		}
	}

	/**
	 * 获取上一次登陆的地址
	 * @param request
	 * @return
	 * @throws MyException
	 */
	@PostMapping("/getLastCity")
	public ResponseBean getLastCity(HttpServletRequest request) throws MyException {
		logBefore(logger,"获取上一次登陆的地址");
		Map<String, Object> reqMap = new HashMap<>();
		reqMap.put("u_id", getCurrentUser(request).getId());
		Map<String, Object> resultMap = appService.getLastCity(reqMap);
		logAfter(logger);
		if (resultMap == null) {
			return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",new HashMap<>());
		}
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resultMap);
	}

	/**
	 * 修改上一次登陆的地址
	 * @param str
	 * @param request
	 * @return
	 * @throws MyException
	 */
	@PostMapping("/updateLastCity")
	public ResponseBean updateLastCity(@RequestBody String str, HttpServletRequest request) throws MyException {
		logBefore(logger,"修改上一次登陆的地址");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		User user = getCurrentUser(request);
		reqMap.put("u_id", user.getId());
		int result = appService.updateLastCity(reqMap);
		logAfter(logger);
		if (result == 1) {
			return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",result);
		} else {
			return new ResponseBean(Constants.CODE_HANDEL_FAILED, "操作失败", null);
		}
	}

	/**
	 * 新增评价
	 * @param str
	 * @param request
	 * @return
	 * @throws MyException
	 */
	@PostMapping("/addEvaluate")
	public ResponseBean addEvaluate(@RequestBody String str, HttpServletRequest request) throws MyException {
		logBefore(logger,"新增评价");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		if (Integer.parseInt(reqMap.get("description_coincidence").toString()) <= 0 ||
				Integer.parseInt(reqMap.get("service_speed").toString()) <= 0 ||
					Integer.parseInt(reqMap.get("service_attitude").toString()) <= 0 ) {
			return new ResponseBean(Constants.CODE_HANDEL_FAILED,"评分必选",null);
		}
		User user = getCurrentUser(request);
		reqMap.put("u_id", user.getId());
		reqMap.put("u_name", user.getUser_name());
		ResponseBean result = appService.addEvaluate(reqMap);
		logAfter(logger);
		return result;
	}

	/**
	 * 获取评价
	 * @param str
	 * @param request
	 * @return
	 * @throws MyException
	 */
	@PostMapping("/getEvaluate")
	public ResponseBean getEvaluate(@RequestBody String str, HttpServletRequest request) throws MyException {
		logBefore(logger,"获取评价");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		Map<String, Object> resultMap = appService.getEvaluate(reqMap);
		logAfter(logger);
		if (resultMap == null) {
			return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",new HashMap<>());
		}
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resultMap);
	}

	/**
	 * 获取消息列表
	 * @param str
	 * @param request
	 * @return
	 * @throws MyException
	 */
	@PostMapping("/getMessageList")
	public ResponseBean getMessage(@RequestBody String str, HttpServletRequest request) throws MyException {
		logBefore(logger,"获取消息列表");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		reqMap.put("u_id", getCurrentUser(request).getId());
		Map<String, Object> resultMap = appService.getMessage(reqMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resultMap);
	}

	/**
	 * 获取未读消息个数
	 * @param str
	 * @param request
	 * @return
	 * @throws MyException
	 */
	@PostMapping("/getMessageFlagCount")
	public ResponseBean getMessageFlagCount(@RequestBody String str, HttpServletRequest request) throws MyException {
		logBefore(logger,"获取未读消息个数");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		reqMap.put("s_id", getCurrentUser(request).getS_id());
		Integer result = appService.getMessageFlagCount(reqMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",result);
	}

	/**
	 * 更新消息列表
	 * @param str
	 * @param request
	 * @return
	 * @throws MyException
	 */
	@PostMapping("/updateMessage")
	public ResponseBean updateMessage(@RequestBody String str, HttpServletRequest request) throws MyException {
		logBefore(logger,"批量更新消息列表");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		if (reqMap.get("id") == null) {
			return new ResponseBean(Constants.CODE_HANDEL_FAILED,"操作失败，id为空",null);
		}
		int result = appService.updateMessage(reqMap);
		if (result > 0) {
			return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",null);
		}else {
			return new ResponseBean(Constants.CODE_HANDEL_FAILED,"操作失败",null);
		}
	}

	/**
	 * 获取历史搜索指标
	 * @return
	 * @throws MyException
	 */
	@PostMapping("/getHistorySearchTarget")
	public ResponseBean getHistorySearchTarget(HttpServletRequest request) throws MyException {
		logBefore(logger,"获取历史搜索指标");
		Map<String, Object> reqMap = new HashMap<>(16);
		reqMap.put("u_id", getCurrentUser(request).getId());
		Map<String, Object> resultMap = appService.getHistorySearchTarget(reqMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resultMap);
	}

	/**
	 * 新增历史搜索指标
	 * @param str
	 * @return
	 * @throws MyException
	 */
	@PostMapping("/addHistorySearchTarget")
	public ResponseBean addHistorySearchTarget(@RequestBody String str, HttpServletRequest request) throws MyException {
		logBefore(logger,"新增历史搜索指标");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		if (StringUtils.isBlank(reqMap.get("target").toString())) {
			throw new MyException(Constants.CODE_HANDEL_FAILED, "指标名称不能为空");
		}
		User user = getCurrentUser(request);
		reqMap.put("u_id", user.getId());
		reqMap.put("u_name", user.getUser_name());
		int result = appService.addHistorySearchTarget(reqMap);
		logAfter(logger);
		if (result == 0) {
			return new ResponseBean(Constants.CODE_HANDEL_FAILED, "新增失败", result);
		}
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",result);
	}

	/**
	 * 删除历史搜索指标
	 * @return
	 * @throws MyException
	 */
	@PostMapping("/deleteHistorySearchTarget")
	public ResponseBean deleteHistorySearchTarget(HttpServletRequest request) throws MyException {
		logBefore(logger,"删除历史搜索指标");
		Map<String, Object> reqMap = new HashMap<>(16);
		reqMap.put("u_id", getCurrentUser(request).getId());
		int result = appService.deleteHistorySearchTarget(reqMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",result);
	}

	/**
	 * 车辆历史数据
	 * @param str
	 * @return
	 * @throws MyException
	 */
	@PostMapping("/carHistoricalData")
	public ResponseBean carHistoricalData(@RequestBody String str) throws MyException {
		logBefore(logger,"车辆历史数据");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date afterDate = new Date(System.currentTimeMillis() + 60000);
		String nowtime = sdf.format(afterDate);
		String endTime = reqMap.get("endTime").toString();
		try {
			//判断结束时间是否大于当前时间
			if (sdf.parse(endTime).getTime() > sdf.parse(nowtime).getTime()) {
				throw new MyException(Constants.CODE_HANDEL_FAILED, "请选择正确的时间");
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		Map<String, Object> resultMap=appService.carHistoricalData(reqMap);
		logAfter(logger);
		if (resultMap == null) {
			return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",new HashMap<>());
		}
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resultMap);
	}

	/**
	 * 车辆历史数据
	 * @param str
	 * @return
	 * @throws MyException
	 */
	@PostMapping("/carHistoricalDataNew")
	public ResponseBean carHistoricalDataNew(@RequestBody String str) throws MyException {
		logBefore(logger,"车辆历史数据");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date afterDate = new Date(System.currentTimeMillis() + 60000);
		String nowtime = sdf.format(afterDate);
		String endTime = reqMap.get("endTime").toString();
		try {
			//判断结束时间是否大于当前时间
			if (sdf.parse(endTime).getTime() > sdf.parse(nowtime).getTime()) {
				throw new MyException(Constants.CODE_HANDEL_FAILED, "请选择正确的时间");
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		Map<String, Object> resultMap=appService.carHistoricalDataNew(reqMap);
		logAfter(logger);
		if (resultMap == null) {
			return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",new HashMap<>());
		}
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resultMap);
	}

	/**
	 * PC端车辆历史数据
	 * @param str
	 * @return
	 * @throws MyException
	 */
	@PostMapping("/carHistoricalDataPC")
	public ResponseBean carHistoricalDataPC(@RequestBody String str) throws MyException {
		logBefore(logger,"PC端车辆历史数据");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date afterDate = new Date(System.currentTimeMillis() + 60000);
		String nowtime = sdf.format(afterDate);
		String endTime = reqMap.get("endTime").toString();
		try {
			//判断结束时间是否大于当前时间
			if (sdf.parse(endTime).getTime() > sdf.parse(nowtime).getTime()) {
				throw new MyException(Constants.CODE_HANDEL_FAILED, "请选择正确的时间");
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		Map<String, Object> resultMap=appService.carHistoricalDataPC(reqMap);
		logAfter(logger);
		if (resultMap == null) {
			return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",new HashMap<>());
		}
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resultMap);
	}

	/**
	 * 车辆历史数据折线图
	 * @param str
	 * @return
	 * @throws MyException
	 */
	@PostMapping("/carHistoricalDataLine")
	public ResponseBean carHistoricalDataLine(@RequestBody String str, HttpServletRequest request) throws MyException {
		logBefore(logger,"车辆历史数据折线图");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		String nowtime = sdf.format(date);
		String endTime = reqMap.get("endTime").toString();
		try {
			//判断结束时间是否大于当前时间
			if (sdf.parse(endTime).getTime() > sdf.parse(nowtime).getTime()) {
				throw new MyException(Constants.CODE_HANDEL_FAILED, "请选择正确的时间");
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		if (StringUtils.isBlank(reqMap.get("target").toString())) {
			throw new MyException(Constants.CODE_HANDEL_FAILED, "指标名称不能为空");
		}
		Map<String, Object> resultMap=appService.carHistoricalDataLine(reqMap);
		logAfter(logger);
		if (resultMap == null) {
			return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",new HashMap<>());
		}
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resultMap);
	}


	/**
	 *  车辆履历
	 * @param str
	 * @param request
	 * @return
	 * @throws MyException
	 */
	@PostMapping("/getCarRecord")
	public ResponseBean carRecord(@RequestBody String str, HttpServletRequest request) throws MyException {
		logBefore(logger, "车辆履历");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		reqMap.put("s_id", getCurrentUser(request).getS_id());
		List<Map<String, Object>> resultMap=appService.getCarRecord(reqMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resultMap);
	}


	/**
	 *  推荐套餐
	 * @param str
	 * @param request
	 * @return
	 * @throws MyException
	 */
	@PostMapping("/maintenanceRecommendation")
	public ResponseBean maintenanceRecommendation(@RequestBody String str, HttpServletRequest request) throws MyException {
		logBefore(logger, "保养套餐_获取保养套餐分组下的时长");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		reqMap.put("s_id", getCurrentUser(request).getS_id());
		Map<String, Object> resultMap=upkeepService.maintenanceRecommendation(reqMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resultMap);
	}

	/**
	 *  推荐套餐
	 * @param str
	 * @param request
	 * @return
	 * @throws MyException
	 */
	@PostMapping("/maintenanceRecommendationNew")
	public ResponseBean maintenanceRecommendationNew(@RequestBody String str, HttpServletRequest request) throws MyException {
		logBefore(logger, "保养套餐_获取保养套餐分组下的时长");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		reqMap.put("s_id", getCurrentUser(request).getS_id());
		Map<String, Object> resultMap=upkeepService.maintenanceRecommendationNew(reqMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resultMap);
	}

	/**
	 *  车辆轨迹
	 * @param str {c_id:车辆id， }
	 * @param request
	 * @return
	 * @throws MyException
	 */
	@PostMapping("/trajectory")
	public ResponseBean trajectory(@RequestBody String str, HttpServletRequest request) {
		logBefore(logger, "车辆轨迹");
		Map<String, Object> trajectoryMap = null;
		try {
			Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
			trajectoryMap = appService.getTrajectoryYD(reqMap);
		} catch (Exception e) {
			return new ResponseBean(Constants.CODE_ERROR,"操作失败",trajectoryMap);
		}
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",trajectoryMap);
	}

	/**
	 * 创建工单 - PC端使用
	 * @param str
	 * @param request
	 * @return
	 * @throws MyException
	 */
	@PostMapping("/createOrder")
	public ResponseBean createOrder(@RequestBody String str, HttpServletRequest request) throws MyException {
		logBefore(logger, "创建工单");
		// 获取当前用户的服务商id
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		User user=getCurrentUser(request);
		String s_id = user.getS_id();
		String r_id = user.getR_id();
		String id = user.getId();
		if(user.getR_id().equals(Constants.ROLE_KF)){
			reqMap.put("u_s_id", user.getId());
		}
		reqMap.put("s_id", s_id);
		reqMap.put("current_user_id", user.getId());
		reqMap.put("r_id", r_id);
		reqMap.put("id", id);
		reqMap.put("user", user);
		reqMap.put("user_name", user.getUser_name());
		appService.createOrder(reqMap);
		logAfter(logger);

		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",null);
	}

	/**
	 * 创建工单 - APP端使用
	 * @param str
	 * @param request
	 * @return
	 * @throws MyException
	 */
	@PostMapping("/createOrderNew")
	public ResponseBean createOrderNew(@RequestBody String str, HttpServletRequest request) throws MyException {
		logBefore(logger, "创建工单");
		// 获取当前用户的服务商id
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		User user = getCurrentUser(request);
		String s_id = user.getS_id();
		String r_id = user.getR_id();
		String id = user.getId();
		if(user.getR_id().equals(Constants.ROLE_KF)){
			reqMap.put("u_s_id", user.getId());
		}
		reqMap.put("s_id", s_id);
		reqMap.put("current_user_id", user.getId());
		reqMap.put("r_id", r_id);
		reqMap.put("id", id);
		reqMap.put("user", user);
		reqMap.put("user_name", user.getUser_name());
		String result = appService.createOrderNew(reqMap);
		logAfter(logger);

		if(result == "-1") { // 如果是非车主或司机创建，提高系统得健壮性，暂时后台接口报错(流程上暂时无法使用非司机或车主的账号创建报修保养工单)
			return new ResponseBean(Constants.CODE_HANDEL_FAILED,"操作失败",null);
		}
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",result);
	}

	/**
	 *
	 * @param str
	 * @param request
	 * @return
	 * @throws MyException
	 */
	@PostMapping("/getFaultInfo")
	public ResponseBean getFaultInfo(@RequestBody String str, HttpServletRequest request) throws MyException {
		logBefore(logger, "获取故障类型");
		// 获取当前用户的服务商id
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		String s_id = getCurrentUser(request).getS_id();
		reqMap.put("s_id", s_id);
		//reqMap.put("s_id", "9af0873379454fe886c365440f7b7f86");
		List<Map<String, Object>> resultMap = appService.getFaultInfo(reqMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resultMap);
	}

	@PostMapping("/getUpkeepInfo")
	public ResponseBean getUpkeepInfo(@RequestBody String str, HttpServletRequest request) throws MyException {
		logBefore(logger, "获取保养套餐信息");
		// 获取当前用户的服务商id
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		String s_id = getCurrentUser(request).getS_id();
		reqMap.put("s_id", s_id);
		List<Map<String, Object>> resultMap = appService.getUpkeepInfo(reqMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resultMap);
	}

	@PostMapping("/getOrderInfo")
	public ResponseBean getOrderInfo(@RequestBody String str, HttpServletRequest request) throws MyException {
		logBefore(logger, "获取工单信息");
		// 获取当前用户的服务商id
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		User currentUser = getCurrentUser(request);
		String sId = currentUser.getS_id();
		reqMap.put("s_id", sId);
		// 获取当前用户的管辖区域
		if (StringUtils.isBlank(reqMap.get("order_id").toString()) && !Constants.ROLE_GLY.equals(currentUser.getR_id()) && !Constants.ROLE_CZ.equals(currentUser.getR_id())
				&& !Constants.ROLE_SJ.equals(currentUser.getR_id())) {
			reqMap.put("precinctRegions", String.join(",", appService.getPrecinctRegionNumbers(currentUser.getId(), currentUser.getS_id())));
		}
		reqMap.put("currentUserRoleId", currentUser.getR_id());
		List<Map<String, Object>> resultMap = appService.getOrderInfo(currentUser, reqMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resultMap);
	}


	@PostMapping("/updateOrderInfo")
	public ResponseBean updateOrderInfo(@RequestBody String str, HttpServletRequest request) throws MyException {
		logBefore(logger, "获取工单信息12121X");
		// 获取当前用户的服务商id
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		User currentUser = getCurrentUser(request);
		if(currentUser.getR_id().equals("1")){
			reqMap.put("u_s_id", currentUser.getId());
		}
		reqMap.put("s_id", currentUser.getS_id());
		reqMap.put("r_id", currentUser.getR_id());
		reqMap.put("id", currentUser.getId());
		reqMap.put("user_name", currentUser.getUser_name());
		reqMap.put("remaining_sum", currentUser.getRemaining_sum());
		reqMap.put("credit_limit", currentUser.getCredit_limit());

		ResponseBean responseBean = appService.updateOrderInfo(reqMap);
		logAfter(logger);
		return responseBean;
	}




	/**
	 * 完成工单
	 * @param str
	 * @param request
	 * @return
	 * @throws MyException
	 */
	@PostMapping("/completeOrderInfo")
	public ResponseBean completeOrderInfo(@RequestBody String str, HttpServletRequest request) throws MyException {

		// 获取当前用户的服务商id
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		User currentUser = getCurrentUser(request);
		if(currentUser.getR_id().equals("1")){
			reqMap.put("u_s_id", currentUser.getId());
		}
		reqMap.put("s_id", currentUser.getS_id());
		reqMap.put("r_id", currentUser.getR_id());
		reqMap.put("id", currentUser.getId());
		reqMap.put("user_name", currentUser.getUser_name());
		reqMap.put("remaining_sum", currentUser.getRemaining_sum());
		reqMap.put("credit_limit", currentUser.getCredit_limit());

		ResponseBean responseBean = appService.completeOrderInfo(reqMap);
		logAfter(logger);
		return responseBean;
	}

	/**
	 * 提交返修
	 * @param str
	 * @param request
	 * @return
	 * @throws MyException
	 */
	@PostMapping("/returnRepair")
	public ResponseBean returnRepair(@RequestBody String str, HttpServletRequest request) throws MyException {

		// 获取当前用户的服务商id
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		User currentUser = getCurrentUser(request);
		if(currentUser.getR_id().equals("1")){
			reqMap.put("u_s_id", currentUser.getId());
		}
		reqMap.put("s_id", currentUser.getS_id());
		reqMap.put("r_id", currentUser.getR_id());
		reqMap.put("id", currentUser.getId());
		reqMap.put("user_name", currentUser.getUser_name());
		reqMap.put("remaining_sum", currentUser.getRemaining_sum());
		reqMap.put("credit_limit", currentUser.getCredit_limit());

		ResponseBean responseBean = appService.returnRepair(reqMap);
		logAfter(logger);
		return responseBean;
	}

	/**
	 * 保存工单优惠
	 * @param str
	 * @param request
	 * @return
	 * @throws MyException
	 */
	@PostMapping("/saveOrderDiscount")
	public ResponseBean saveOrderDiscount(@RequestBody String str, HttpServletRequest request) throws MyException {
		logBefore(logger, "保存工单优惠");
		// 获取当前用户的服务商id
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		User currentUser = getCurrentUser(request);
		appService.saveOrderDiscount(currentUser, reqMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", true);
	}

	/**
	 * 车主解除司机
	 * @param str
	 * @return
	 */
	@RequestMapping(value = "/removeOwnerDriver", method = RequestMethod.POST)
	@ResponseBody
	public ResponseBean removeOwnerDriver(@RequestBody String str) {
		logBefore(logger, "车主解除司机");
		JSONObject reqObj = JSONObject.parseObject(str);
		try {
			Boolean condition = appService.removeOwnerDriver(reqObj);
			if(condition == true){
				return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",null);
			}else{
				return new ResponseBean(Constants.CODE_HANDEL_FAILED,"操作失败",null);
			}
		}catch (Exception e) {
			logger.error(e.toString(), e);
			return new ResponseBean(Constants.CODE_ERROR,"操作失败",null);
		}
	}

	/**
	 * 车主绑定车辆和司机
	 * @param str
	 * @return
	 */
	@RequestMapping(value = "/createOwnerCar", method = RequestMethod.POST)
	@ResponseBody
	public Object createOwnerCar(@RequestBody String str,HttpServletRequest request) throws MyException{
		logBefore(logger, "车主绑定车辆或司机");
		String id = getCurrentUser(request).getId();
		JSONObject reqObj = JSONObject.parseObject(str);
		reqObj.put("id",id);
		JSONObject resultObj = new JSONObject();
		int code = Constants.CODE_ERROR;
		String message = "";
        int result = appService.createOwnerCar(reqObj);
        if(result>0){
            code = Constants.CODE_SUCCESS;
            message = "车主绑定车辆或司机成功";
        }else if(result<0){
            code = Constants.CODE_HANDEL_FAILED;
            message = "车辆已绑定";
        }else{
            code = Constants.CODE_HANDEL_FAILED;
            message = "车主绑定车辆或司机失败";
        }

        resultObj.put("code", code);
        resultObj.put("message", message);
        logAfter(logger);
		return resultObj;
	}

	/**
	 * 获取司机
	 * @param str
	 * @return
	 */
	@RequestMapping(value = "/getOwnerDriver", method = RequestMethod.POST)
	@ResponseBody
	public Object getOwnerDriver(@RequestBody String str) {
		logBefore(logger, "车主绑定车辆或司机");
		JSONObject reqObj = JSONObject.parseObject(str);
		JSONObject resultObj = new JSONObject();
		int code = Constants.CODE_ERROR;
		String message = "";
		try {
			Object orderObj = appService.getOwnerDriver(reqObj);
			resultObj.put("data", orderObj);
			code = Constants.CODE_SUCCESS;
		}catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			resultObj.put("code", code);
			resultObj.put("message", message);
			logAfter(logger);
		}
		return resultObj;
	}
	/**
	 * 车主添加司机
	 * @param str
	 * @return
	 */
	@RequestMapping(value = "/addOwnerDriver", method = RequestMethod.POST)
	@ResponseBody
	public Object addOwnerDriver(@RequestBody String str) {
		logBefore(logger, "车主添加司机");
		Map<String, Object> reqMap = JSONObject.parseObject(str,Map.class);
		try {
			Boolean condition = appService.addOwnerDriver(reqMap);
			if(condition == true){
				return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",null);
			}else{
				return new ResponseBean(Constants.CODE_HANDEL_FAILED,"操作失败",null);
			}
		}catch (Exception e) {
			logger.error(e.toString(), e);
			return new ResponseBean(Constants.CODE_ERROR,"操作失败",null);
		}
	}

	/**
	 * 获取用户名下车辆信息
	 *
	 * @param str
	 * @return
	 */
	@RequestMapping(value = "/getCarInfo", method = RequestMethod.POST)
	@ResponseBody
	public Object getCarInfo(@RequestBody String str,HttpServletRequest request) {
		logBefore(logger, "获取车辆信息");
		JSONObject reqObj = JSONObject.parseObject(str);
		JSONObject resultObj = new JSONObject();
		String code = String.valueOf(Constants.CODE_ERROR);
		String message = "";
		try {
			//			if (reqObj.get("s_id") != null && !reqObj.get("s_id").equals("")) {
			Object carObj = appService.getCarInfo(reqObj);
			resultObj.put("data", carObj);
			if (carObj == null) {
				message = "未查询到数据";
			}
			code = String.valueOf(Constants.CODE_SUCCESS);
			//			} else {
			//				code = Constants.CODE_PARAM_ERROR;
			//				message = "参数错误,请检查参数名和参数值";
			//			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			resultObj.put("code", Integer.valueOf(code));
			resultObj.put("message", message);
			logAfter(logger);
		}
		return resultObj;
	}

	/**
	 * 车辆工时统计
	 *
	 * @param str
	 * @return
	 */
	@PostMapping("getCarWorkingHoursStatistics")
	@ResponseBody
	public ResponseBean getCarWorkingHoursStatistics(@RequestBody String str, HttpServletRequest request) throws MyException, UnsupportedEncodingException {
		logBefore(logger, "车辆工时统计");
		JSONObject reqObj = JSONObject.parseObject(str);
		User currentUser = getCurrentUser(request);
		Map<String, Object> carDataList = appService.getCarWorkingHoursStatistics(currentUser, reqObj);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", carDataList);
	}


	@PostMapping("/updateOrderStatus")
	public ResponseBean updateOrderStatus(@RequestBody String str,HttpServletRequest request) throws MyException {
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		appService.updateOrderStatus(reqMap);
		return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", null);
	}

	/**
	 * 修改密码
	 * @param str
	 * @param request
	 * @return
	 * @throws MyException
	 */
	@PostMapping("/updatePassWord")
	public ResponseBean updatePassWord(@RequestBody String str,HttpServletRequest request) throws MyException {
		logBefore(logger, "修改密码");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		Map<String, Object> map = new HashMap<String, Object>();
		String currentUserId = getCurrentUser(request).getId();
		String userAccount = reqMap.get("userId").toString(); // userAccount 等于用户(修改密码的用户)的手机号(手机号即为用户名)
		String newPassword = reqMap.get("newPassWord").toString();
		String newPassWordMD5 = MD5.md5(newPassword);
		String userPhone = reqMap.get("userPhone").toString();

		if (reqMap.containsKey("oldPassWord")) {  // App 端的修改密码逻辑
			String oldPassWord = (String) reqMap.get("oldPassWord");
			Boolean condition = appService.isCorrectPassWord(userAccount, oldPassWord);
			if (condition == true) {
				map.put("userId", userAccount);
				map.put("newPassWord", newPassWordMD5);
				int result = appService.updatePassWord(map);
				if (result == 1) {
					// 添加用户修改密码的历史记录
					map.put("user_id", currentUserId);
					map.put("password", newPassword);
					map.put("password_md5", newPassWordMD5);
					map.put("user_phone", userPhone);
					map.put("modify_user_id", currentUserId);
					userService.recordUserPassword(map);

					return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",null);
				} else {
					return new ResponseBean(Constants.CODE_HANDEL_FAILED,"操作失败！",null);
				}
			} else {
				return new ResponseBean(Constants.CODE_HANDEL_FAILED,"操作失败,手机号码或旧密码输入错误",null);
			}
		} else { // PC端的修改密码逻辑
			map.put("userId", userAccount);
			map.put("newPassWord", newPassWordMD5);
			int result = appService.updatePassWord(map);
			if (result == 1) {
				// 添加用户修改密码的历史记录
				map.put("user_id", currentUserId);
				map.put("password", newPassword);
				map.put("password_md5", newPassWordMD5);
				map.put("user_phone", userPhone);
				map.put("modify_user_id", currentUserId);
				userService.recordUserPassword(map);

				return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",null);
			} else {
				return new ResponseBean(Constants.CODE_HANDEL_FAILED,"操作失败",null);
			}
		}
	}

	/**
	 * 修改个人信息
	 */
	@PostMapping("/updateUserInfo")
	public ResponseBean updateUserInfo(@RequestBody String str,HttpServletRequest request) throws MyException {
		logBefore(logger, "修改密码");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		reqMap.put("userId",getCurrentUser(request).getId());
		int  result = appService.updateUserInfo(reqMap);
		if (result == 1) {
			return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",result);
		}
		return new ResponseBean(Constants.CODE_HANDEL_FAILED,"操作失败",result);
	}

	/**
	 * 短信接口
	 * @throws Exception
	 */
	@PostMapping("/toPhoneInfo")
	public ResponseBean toPhoneInfo(@RequestBody String str) throws Exception {
		logBefore(logger, "调用短信接口实现发短信");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		String phonenum = reqMap.get("phonenum").toString();
		String content = reqMap.get("content").toString();
		int number = Random.getRandom();
		redisUtil.set("code", number, Constants.EXPIRE_TIME);

		HttpClient httpClient = null;;
		httpClient = new HTTPSTrustClient().init();
		Map<String, String> paramHeader = new HashMap<>();
		paramHeader.put("Accept", "application/xml");
		Map<String, String> paramBody = new HashMap<>();
		paramBody.put("phonenum", phonenum);
		paramBody.put("content", content);
		String url = "https://cloud.zoweunion.com/API/Contact";
		String result = HTTPSClientUtil.doPost(httpClient, url, paramHeader, paramBody);

		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",result);
	}

	/**
	 * 短信接口
	 * @throws Exception
	 */
	@PostMapping("/sendPhoneInfo")
	public ResponseBean sendPhoneInfo(@RequestBody String str) throws Exception {
		logBefore(logger, "调用短信接口实现发短信");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		Map<String, String> map = new HashMap<>();
		Integer number = null;
		String phoneNum = reqMap.get("phonenum").toString();
		String securityCode;
		// 判断是否为忘记密码发送验证码操作
		if (reqMap.get("source") != null && StringUtils.isNotBlank(reqMap.get("source").toString())
				&& "forgetPassword".equals(reqMap.get("source").toString())) {
			Map<String, Object> userMap = userService.getUserInfoByAccount(reqMap.get("phonenum").toString());
			if (userMap == null) {
				return new ResponseBean(Constants.CODE_ACCESS_PROHIBITED, "该账号不存在", false);
			}
			securityCode = UuidUtil.get32UUID();
			redisUtil.set(phoneNum + "securityCode", securityCode, (long) (5 * 60));
			map.put("securityCode", securityCode);
		}
		//先从redis中获取短信验证码看是否过期
		number = (Integer) redisUtil.get(reqMap.get("phonenum").toString() + "code");
		//已经过期
		if (number == null) {
			//生成短信验证码
			number = Random.getRandom();
			map.put("number", number + "");
			String template = "【机修狮】您的验证码是：%s，祝你工作愉快。机修狮 - 远程实时监控工程机械车辆运行数据，全品牌、多种类、新老机统一管理。";
			//获取电话号码
			String content = String.format(template, String.valueOf(number));
			String resO = SmsUtil.sendSms(phoneNum, content);
			if (StringUtils.isBlank(resO)) {
				//将生成的验证码存在redis中
				redisUtil.set(phoneNum + "code", number, Constants.EXPIRE_TIME);
				return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", map);
			}
			return new ResponseBean(Constants.CODE_HANDEL_FAILED, resO, null);
			//未过期
		} else {
			map.put("number", number + "");
			if (redisUtil.get(phoneNum + "securityCode") != null) {
				securityCode = redisUtil.get(phoneNum + "securityCode").toString();
				map.put("securityCode", securityCode);
			}
			return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", map);
		}
	}

	/**
	 * 获取修工听诊
	 * @throws Exception
	 */
	@RequestMapping(value = "/getWorker", method = RequestMethod.POST)
	@ResponseBody
	public Object getWorker(@RequestBody String str) {
		logBefore(logger, "获取工单信息");
		JSONObject reqObj = JSONObject.parseObject(str);
		JSONObject resultObj = new JSONObject();
		int code = Constants.CODE_ERROR;
		String message = "";
		try {
			Object orderObj = appService.getWorker(reqObj);
			resultObj.put("data", orderObj);
			code = Constants.CODE_SUCCESS;
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			resultObj.put("code", code);
			resultObj.put("message", message);
			logAfter(logger);
		}
		return resultObj;
	}

	/**
	 * 支付宝支付调用支付宝支付接口
	 * @param model，id，payables，
	 * @throws IOException，AlipayApiException
	 * @return Object
	 * @author 王春伟
	 */
	@PostMapping("pcalipaySum")
	public Object pcAlipayIumpSum(Model model, @RequestBody String str, HttpServletResponse response)
			throws Exception {
		logBefore(logger, "支付宝支付接口");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		//订单金额(必填)
		String payables = reqMap.get("payables").toString();
		//订单名称(必填)
		String subject = reqMap.get("subject").toString();
		//商品描述(可空)
		String body = reqMap.get("body").toString();
		//TODO:先判断客户下单的商品有没有库存

		// 获得初始化的AlipayClient
		AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id,
				AlipayConfig.merchant_private_key, "json", AlipayConfig.charset,
				AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
		// 设置请求参数
		AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
		alipayRequest.setReturnUrl(AlipayConfig.return_url);
		alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		// 商户订单号，商户网站订单系统中唯一订单号，必填
		String out_trade_no = sdf.format(new Date());
		// 付款金额，必填
		String total_amount = payables.replace(",", "");
		alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\"," + "\"total_amount\":\"" + total_amount
				+ "\"," + "\"subject\":\"" + subject + "\"," + "\"body\":\"" + body + "\","
				+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
		// 请求
		String result = alipayClient.pageExecute(alipayRequest).getBody();
		// System.out.println(result);
		response.setContentType("text/html; charset=gbk");
		PrintWriter out = response.getWriter();
		out.print(result);
		return null;
	}


	/**
	 * 支付宝支付调用支付宝支付接口
	 * @param str，
	 * @throws IOException，AlipayApiException
	 * @return Object
	 * @author 王春伟
	 */
	@PostMapping("alipaySum")
	public ResponseBean alipayIumpSum(@RequestBody String str, HttpServletResponse response)
			throws Exception {
		logBefore(logger, "支付宝支付接口");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		//订单金额(必填)
		String payables = reqMap.get("payables").toString();
		//订单名称(必填)
		String subject = reqMap.get("subject").toString();
		//商品描述(可空)
		String body = reqMap.get("body").toString();
		//TODO:先判断客户下单的商品有没有库存

		//最终返回加签之后的，app需要传给支付宝app的订单信息字符串
		String orderString = "";
		//实例化客户端（参数：网关地址、商户appid、商户私钥、格式、编码、支付宝公钥、加密类型），为了取得预付订单信息
		AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id,
				AlipayConfig.merchant_private_key, "json", AlipayConfig.charset,
				AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

		try{
			//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
			AlipayTradeAppPayRequest ali_request = new AlipayTradeAppPayRequest();

			//SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式
			AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();

			//业务参数传入,可以传很多，参考API
			//model.setPassbackParams(URLEncoder.encode(request.getBody().toString())); //公用参数（附加数据）
			model.setBody(body);            //对一笔交易的具体描述信息。如果是多种商品，请将商品描述字符串累加传给body。
			model.setSubject(subject);         //商品名称
			model.setOutTradeNo(subject);      //商户订单号(自动生成)
			// model.setTimeoutExpress("30m");     //交易超时时间
			model.setTotalAmount(payables);     //支付金额
			model.setProductCode("QUICK_MSECURITY_PAY");      //销售产品码（固定值）
			ali_request.setBizModel(model);
			ali_request.setNotifyUrl(AlipayConfig.notify_url);    //异步回调地址（后台）
			ali_request.setReturnUrl(AlipayConfig.return_url);   //同步回调地址（APP）
			AlipayTradeAppPayResponse alipayTradeAppPayResponse = alipayClient.sdkExecute(ali_request);
			orderString = alipayTradeAppPayResponse.getBody();
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("与支付宝交互出错，未能生成订单，请检查代码！");
		}
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",orderString);

	}

	/**
	 * 支付宝支付完成回调验证操作
	 * @param response，request
	 * @throws Exception
	 * @return void
	 * @author 王春伟
	 */

	@PostMapping("notify_url")
	public void Notify(HttpServletResponse response, HttpServletRequest request) throws Exception {
		System.out.println("----------------------------notify_url------------------------");
		// 商户订单号
		String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "GBK");
		// 付款金额
		String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "GBK");
		// 支付宝交易号
		String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "GBK");
		// 交易说明
		String cus = new String(request.getParameter("body").getBytes("ISO-8859-1"), "GBK");
		// 交易状态
		String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "GBK");
		if (trade_status.equals("TRADE_SUCCESS")) {//支付成功商家操作
			System.out.println("************************************");
			//支付成功的业务逻辑

		}
	}

	/**
	 * 支付宝支付完成同步通知的页面的Controller
	 * @throws InterruptedException
	 */
	@PostMapping("return_url")
	public String return_url() throws InterruptedException {
		return "alipayexit";
	}

	/**
	 * 个人中心-信用额度列表
	 */
	@PostMapping("/getOrderListByPayType")
	public ResponseBean getOrderListByPayType(@RequestBody String str,HttpServletRequest httpServletRequest) throws MyException{
		logBefore(logger, "个人中心-信用额度列表");
		User currentUser = getCurrentUser(httpServletRequest);
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);

		List<Map<String, Object>> ordreList = appService.getOrderListByPayType(currentUser, reqMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", ordreList);
	}

	/**
	 * 发送短信提醒
	 */
	@PostMapping("/sendMmsRemind")
	public ResponseBean sendMmsRemind(@RequestBody String str,HttpServletRequest httpServletRequest) throws MyException{
		logBefore(logger, "发送短信提醒");
		User currentUser = getCurrentUser(httpServletRequest);
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		appService.sendSMSRemind(currentUser, reqMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", true);
	}

	/**
	 * 解决数据库密码没有加密的问题(测试用)
	 *
	 * @throws InterruptedException
	 */
	@PostMapping("updatePasswordToMd5")
	public String updatePasswordToMd5() throws InterruptedException {

		List<Map<String,String>> list = appDap.selectPassWord1();
		list.forEach(map -> appDap.updateToMd5(map.get("id"),MD5.md5(map.get("user_password"))));
		return null;
	}

	/**
	 * 人脸授权页面
	 * @throws MyException
	 */
	@PostMapping("humanFaceAuthorization")
	public ResponseBean humanFaceAuthorization(@RequestBody String str,HttpServletRequest httpServletRequest) throws MyException {
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);

        int random1 = (int)(Math.random()*9+1);
        int random2 = (int)(Math.random()*9+1);
        int random3 = (int)(Math.random()*9+1);
        int random4 = (int)(Math.random()*9+1);

        reqMap.put("face_id",String.valueOf(random1)+String.valueOf(random2)+String.valueOf(random3)+String.valueOf(random4));
		reqMap.put("status",1);

		appService.updateHumanFaceAuthorization(reqMap);

		return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", true);
	}

	/**
	 * 获取人脸的faceid
	 * @throws MyException
	 */
	@PostMapping("getHumanFaceId")
	public ResponseBean getHumanFaceId(@RequestBody String str,HttpServletRequest httpServletRequest) throws MyException {
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);

		Map<String,Object> resultMap = appService.getHumanFaceId(reqMap);

		return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", resultMap);
	}

	/**
	 * 删除人脸
	 * @throws MyException
	 */
	@PostMapping("deleteHumanFaceId")
	public ResponseBean deleteHumanFaceId(@RequestBody String str,HttpServletRequest httpServletRequest) throws MyException {
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);

		appService.deleteHumanFaceId(reqMap);

		return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", true);
	}

	/**
	 * 查询模板
	 * @throws MyException
	 */
	@GetMapping("selectTemplateColumn")
	public ResponseBean selectTemplateColumn(@RequestParam Map<String, Object> reqMap) throws MyException {
		List<Map<String, Object>> maps = appService.selectTemplateColumn(reqMap);
		return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", maps);
	}

	/**
	 * 查询实时故障
	 * @throws MyException
	 */
	@GetMapping("selectFaultData")
	public ResponseBean selectFaultData(@RequestParam Map<String, Object> reqMap) throws MyException {
		List<Map<String, Object>> maps = appService.selectFaultData(reqMap);
		return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", maps);
	}

	/**
	 * 申请试用
	 * @throws MyException
	 */
	@PostMapping("trialApplication")
	public ResponseBean trialApplication(@RequestBody Map<String, Object> reqMap) throws MyException {
		appService.trialApplication(reqMap);
		return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", null);
	}

	/**
	 * 获取APP和PC配置(APP首页、PC登录页变黑白样式等配置)
	 * @param appName
	 * @return
	 */
	@GetMapping("getAppPcSetting")
	public ResponseBean getAppPcSetting(String appName) {
		return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", appService.getAppPcSetting(appName));
	}


	/**
	 * 获取金融平台下车主的所有存在账期的车
	 */
	@GetMapping("/getAllCarInFinancialByOwnerId")
	public ResponseBean getAllCarInFinancialByOwnerId(HttpServletRequest request) throws MyException {
		List<Map<String, Object>> list = appService.getAllCarInFinancialByOwnerId(getCurrentUser(request).getId());
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功", list);
	}


	/**
	 * 金融平台下车主向金融平台申请解锁
	 */
	@PostMapping("/applyUnlock")
	public ResponseBean applyUnlock(@RequestBody Map<String, Object> params, HttpServletRequest request) throws MyException {
		String o_id = getCurrentUser(request).getId();
		String s_id = getCurrentUser(request).getS_id();
		params.put("o_id", o_id);
		params.put("user_id", o_id);
		params.put("s_id", s_id);
		int result = appService.applyUnlock(params);
		if(result == 0) {
			return new ResponseBean(Constants.CODE_ERROR,"操作失败", null);
		}
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功", null);
	}
}